<template>
    <div class="content">
        <card title="标签管理" size="large">
            <el-button plain :icon="RefreshRight" size="default" @click="reset()">重置</el-button>
            <template #main>
                <el-row>
                    <el-col :span="8">
                        <div class="form-item">
                            <span>标签名称</span>
                            <el-input v-model.trim="queryData.labelName" placeholder="请输入标签名称" clearable
                                @keyup.enter.native="search()">
                            </el-input>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="form-item">
                            <span>创建者类型</span>
                            <el-select v-model="queryData.userType" clearable filterable placeholder="请选择创建者类型"
                                @change="search">
                                <el-option label="全部" value=""></el-option>
                                <el-option label="管理员" :value=1></el-option>
                                <el-option label="小程序用户" :value=0></el-option>
                            </el-select>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="btn-item">
                            <el-button type="primary" size="default" plain :icon="Search" @click="search()">
                                搜 索
                            </el-button>
                        </div>
                    </el-col>
                </el-row>
            </template>
        </card>
        <div class="card-content">
            <div class="oper-box">
                <el-button type="primary" :icon="Plus" @click="handleCreate">新 增</el-button>
                <el-button type="primary" plain :icon="Delete" @click="handleBatchDelete" v-show="globalStore.deleteAuthority">批量删除</el-button>
            </div>
            <el-table :data="tableData" ref="multipleTableRef" v-loading="loading" row-key="id" size="default"
                empty-text="暂无数据" highlight-current-row class="primary-table label-table"
                @selection-change="handleSelect" @select-all="handleSelectAll">
                <el-table-column type="selection" width="55" align="center" fixed="left" />
                <el-table-column prop="tag_name" label="标签名称" min-width="120" show-overflow-tooltip
                    fixed="left"></el-table-column>
                <el-table-column prop="creater_type" label="创建用户类型" min-width="120" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.creater_type === 1 ? '管理员' : '小程序用户' }}
                    </template>
                </el-table-column>
                <el-table-column prop="nickname" label="创建用户" min-width="80" show-overflow-tooltip></el-table-column>
                <el-table-column prop="create_time" label="创建时间" min-width="170"
                    show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" align="center" width="150" fixed="right">
                    <template #default="scope">
                        <el-tooltip content="详情" placement="top">
                            <el-button link type="primary" :icon="View" @click="handleDetail(scope.$index, scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="编辑" placement="top">
                            <el-button link type="primary" :icon="Edit" @click="handleEdit(scope.$index, scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link type="primary" :icon="Delete"
                                @click="handleDelete(scope.$index, scope.row)" v-show="globalStore.deleteAuthority">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:page-size="queryData.pageSize" :current-page="queryData.pageNum" background
                layout="total, prev, pager, next" :total="total" :page-sizes="[10, 20, 50, 80, 100]"
                @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </el-pagination>
        </div>
    </div>
    <!-- 详情弹窗 -->
    <el-dialog v-if="dialogDetail" v-model="dialogDetail" title="标签详情" class="log-dialog" :close-on-click-modal="false"
        :close-on-press-escape="false" destroy-on-close append-to-body @befor-close="handleClose">
        <label-details :id="currentRow.tag_id || ''"></label-details>
    </el-dialog>
    <!-- 编辑弹窗 -->
    <el-dialog v-if="dialogEdit" v-model="dialogEdit" :title="editTitle" :close-on-click-modal="false"
        :close-on-press-escape="false" destroy-on-close append-to-body @befor-close="handleClose">
        <el-form :model="formData" :rules="rules" ref="labelForm" :disabled="labelSaveLoading" label-width="100px"
            @submit.enter.prevent>
            <el-form-item label="标签名称:" prop="labelName">
                <el-input v-model.trim="formData.tag_name"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog__footer">
                <el-button type="primary" :loading="labelSaveLoading" :disabled="labelSaveLoading"
                    @click="handleConfirm">确 认</el-button>
                <el-button type="primary" plain :disabled="labelSaveLoading" @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Delete, View, Search, Edit, RefreshRight, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import useGlobalStore from '../../store/modules/global';
import card from '../../components/card/index.vue'
import labelDetails from './components/labelDetails.vue'
import { getTagsByPagination, deleteTagById, modifyTagById,addTag, deleteTagsAmount } from '../../api/tag.ts'

const queryData = ref({
    labelName: null,
    userType: null,
    pageSize: 10,
    pageNum: 1
})
const globalStore = useGlobalStore()
const total = ref(0)
const loading = ref(false)
const multipleSelection = ref([])

const dialogDetail = ref(false)
const currentRow = ref({})
const currentIndex = ref(0)
const dialogEdit = ref(false)
const editTitle = ref('')

const formData = ref({
    tag_name: ''
})
const rules = reactive({
    labelName: [{ reuired: true, message: '请输入标签名称', trigger: 'blur' }]
})
const labelForm = ref(null)
const labelSaveLoading = ref(false)

interface tableDataInterface {
    tag_id: number,
    tag_ame: string,
    creater_type: string,
    nickname: string,
    user_id: number,
    create_time: string
}

//表格部分
// let tableData: tableDataInterface[] = ref([])
let tableData = ref([])

const handleCreate = () => {
    dialogEdit.value = true
    editTitle.value = '新增标签'
}
// 编辑
const handleEdit = (index: number, row: Object) => {
    currentIndex.value = index
    currentRow.value = row
    dialogEdit.value = true
    editTitle.value = '编辑标签'
    formData.value.tag_name = row.tag_name || ''
}
const handleConfirm = () => {
    labelForm.value.validate(async (valid: Boolean) => {
        if (valid) {
            labelSaveLoading.value = true
            // let api = formData.value.id ? '编辑接口' : '新增接口'
            // 调接口
            if (editTitle.value == '编辑标签') {
                const result = await modifyTagById({
                    tag_id: currentRow.value.tag_id,
                    tag_name: formData.value.tag_name
                })
                if (result.code == 1) {
                    ElMessage({
                        type: 'success',
                        message: '修改成功',
                        showClose: true
                    })
                    search()
                    dialogEdit.value = false
                    formData.value.tag_name = ''
                }
            }else if(editTitle.value == '新增标签'){
                const params = {
                    nickname:globalStore.getUserInfo().nickname,
                    tag_name:formData.value.tag_name,
                    create_time:new Date(),
                    creater_type:1
                }
                const result = await addTag(params)
                if(result.code == 1){
                    ElMessage({
                        type: 'success',
                        message: '添加成功',
                        showClose: true
                    })
                    search()
                    dialogEdit.value = false
                    formData.value.tag_name = ''
                }

            }

            // 接口调完
            labelSaveLoading.value = false
        }
    })
}
// 查看详情
const handleDetail = (index: number, row: Object) => {
    currentRow.value = row
    currentIndex.value = index
    dialogDetail.value = true
}
const handleClose = () => {
    currentRow.value = {}
    currentIndex.value = 0
    dialogDetail.value = false
    dialogEdit.value = false
    editTitle.value = ''
    formData.value.labelName = ''
}
// 删除
const handleDelete = (index: Number, row: Object) => {
    ElMessageBox.confirm(`确认删除'${row.tag_name}'？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        // 调删除接口
        const result = await deleteTagById({ tag_id: row.tag_id })
        if (result.code == 1) {
            ElMessage({
                type: 'success',
                message: '删除成功',
                showClose: true
            })
            search()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除！',
            showClose: true
        })
    })
}
// 批量删除
const handleBatchDelete = () => {
    if (!multipleSelection.value.length) {
        ElMessage({
            type: 'warning',
            message: '请先选择标签！',
            showClose: true
        })
        return
    }
    ElMessageBox.confirm('确认删除选中的标签？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async() => {
        // 调批量删除接口
        const result = await deleteTagsAmount({
            tags:multipleSelection.value
        })
        if (result.code == 1) {
            ElMessage({
                type: 'success',
                message: '删除成功',
                showClose: true
            })
            search()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消批量删除！',
            showClose: true
        })
    })
}
// 搜索
const search = async () => {
    // 调获取列表接口
    tableData.value = []
    const result = await getTagsByPagination(queryData.value)
    tableData.value = result.data
    total.value = result.total
}
// 重置
const reset = () => {
    queryData.value.labelName = ''
    queryData.value.userType = ''
    queryData.value.pageNum = 1
    queryData.value.pageSize = 10
    search()
}
const handleSizeChange = (size: Number) => {
    queryData.value.pageSize = size
    queryData.value.pageNum = 1
    search()
}

const handleCurrentChange = (page: Number) => {
    queryData.value.pageNum = page
    search()
}


const handleSelect = (selection: Object) => {
    multipleSelection.value = selection
}
const handleSelectAll = (selection: Object) => {
    multipleSelection.value = selection
}

onMounted(async () => {
    search()
})
</script>

<style lang="less" scoped>
.label-table {
    height: calc(100% - 50px - 50px);
}
</style>
